# -*- coding: utf-8 -*-

"""剑指 Offer II 111. 计算除法
给定一个变量对数组 equations 和一个实数值数组 values 作为已知条件，其中 equations[i] = [Ai, Bi] 和 values[i] 共同表示等式 Ai / Bi = values[i] 。
每个 Ai 或 Bi 是一个表示单个变量的字符串。
另有一些以数组 queries 表示的问题，其中 queries[j] = [Cj, Dj] 表示第 j 个问题，请你根据已知条件找出 Cj / Dj = ? 的结果作为答案。
返回 所有问题的答案 。如果存在某个无法确定的答案，则用 -1.0 替代这个答案。如果问题中出现了给定的已知条件中没有出现的字符串，也需要用 -1.0 替代这个答案。

注意：输入总是有效的。可以假设除法运算中不会出现除数为 0 的情况，且不存在任何矛盾的结果。

示例 1：
输入：equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
输出：[6.00000,0.50000,-1.00000,1.00000,-1.00000]
解释：
条件：a / b = 2.0, b / c = 3.0
问题：a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
结果：[6.0, 0.5, -1.0, 1.0, -1.0 ]

示例 2：
输入：equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]
输出：[3.75000,0.40000,5.00000,0.20000]

示例 3：
输入：equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]
输出：[0.50000,2.00000,-1.00000,-1.00000]

提示：
1 <= equations.length <= 20
equations[i].length == 2
1 <= Ai.length, Bi.length <= 5
values.length == equations.length
0.0 < values[i] <= 20.0
1 <= queries.length <= 20
queries[i].length == 2
1 <= Cj.length, Dj.length <= 5
Ai, Bi, Cj, Dj 由小写英文字母与数字组成"""

class Solution:
    """a/b, b/c --> a/c = a/b * b/c, 根据这个运算结合关系建图，以除数被除数为顶点，相除结果为边，构建双向图。
    权重因为有小数的缘故，以两个整数元组形式给出，2.5 -> (25, 10), 3.0 -> (30, 10), 那么 1/3.0 -> (10, 30)。
    最后将除数与被除数拉通计算，这么做会有效规避计算过程中的四舍五入结果，比如 1/3.0*3.0 = 0.9999。
    这是个稀疏图，图结构以这样实现{x: {y1: (m1, n1), y2: (m2, n2)}, y1: {x: {n1, m1}}}

    题目给出了一个限定是不存在任何矛盾的结果，所以可以用深度优先遍历，找到第一条到达目的的路径便可。
    """
    def divide_path(self, graph:dict, x, y):
        if not (x in graph.keys() and y in graph.keys()):
            return []
        
        if x == y:
            return [(10, 10)]

        success = False
        path_1st = None

        def goto(a, visited:set, path:list):
            nonlocal success, path_1st
            if success:
                return

            for b in graph[a].keys():
                if b in visited:
                    continue

                new_path = path.copy()
                new_path.append(graph[a][b])

                new_visited = visited.copy()
                new_visited.add(b)
                if b == y:
                    success = True
                    path_1st = new_path
                    return
                goto(b, new_visited, new_path)

        goto(x, set([x]), [])

        return path_1st if path_1st else []


    def calcEquation(self, equations: list, values: list, queries: list) -> list:
        graph = dict()
        i = 0
        size = len(equations)
        while i < size:
            x, y, z = equations[i][0], equations[i][1], values[i]
            m = int(z * 10)
            n = 10

            if x not in graph.keys():
                graph[x] = dict()
            graph[x][y] = (m, n)

            if not y in graph.keys():
                graph[y] = dict()
            graph[y][x] = (n, m)

            i += 1

        answers = []
        for query in queries:
            x, y = query[0], query[1]
            path = self.divide_path(graph, x, y)
            if path:
                M, N = 1, 1
                for m, n in path:
                    M *= m
                    N *= n
                answer = M / N
            else:
                answer = -1.0
            answers.append(answer)

        return answers

if __name__ == '__main__':
    print(Solution().calcEquation(equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]))
    print(Solution().calcEquation(equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]))
    print(Solution().calcEquation(equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]))
